package com.eurasia.assignment.infrastructure.hoj;

import com.eurasia.assignment.service.port.out.HOJAuthToken;
import com.eurasia.assignment.service.port.out.AccessHOJAuthorizationPort;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class HOJAuthPersistentAdapter implements AccessHOJAuthorizationPort {
    private final HOJAuthTokenRepository authTokenRepository;
    private final HOJAuthTokenMapper authTokenMapper = HOJAuthTokenMapper.INSTANCE;

    @Override
    public HOJAuthToken save(HOJAuthToken authorization) {
        HOJAuthTokenEntity entity = authTokenMapper.fromDomain(authorization);
        authTokenRepository.save(entity);
        return authTokenMapper.toDomain(entity);
    }

    @Override
    public HOJAuthToken findLatestAuthorization() {
        return authTokenRepository
                .findFirstBySuccessTrueOrderByCreateTimeDesc()
                .map(authTokenMapper::toDomain)
                .orElseThrow(TokenNotFoundException::new);
    }
}
